import { ProForm } from "@/components/ProForm";
import { useState,useEffect } from "react";
import { PageContainer } from "@ant-design/pro-layout";
import { http } from "@/utils/request";
import {
  Button,
  Divider,
  Form,
  Input, message, Modal, Radio, Select,
  Table,
  Pagination,
  type TableColumnsType
} from "antd";

type TableDataType = {
  baseUserId: string;
  baseUserName: string;
  position: string;
  participationEvalu: string;
}

const PostMaintenance = () => {
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const [id,setId] = useState(null);
  const [list, setList] = useState([]);
  const [pageNum,setPageNum] = useState(1);
  const [pageSize,setPageSize] = useState(10);
  const [total,setTotal] = useState();
  const [positionOption,setPositionOption] = useState([]);
  const [selectedValue, setSelectedValue] = useState(null);
  const [selectedLabel, setSelectedLabel] = useState('');
  const [open, setOpen] = useState<boolean>(false);
  const [currentEdit, setCurrentEdit] = useState<Partial<TableDataType>>({});

  const columns: TableColumnsType<TableDataType> = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text, _record, index) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "员工编号",
      dataIndex: "baseUserId"
    },
    {
      align: "center",
      title: "员工姓名",
      dataIndex: "baseUserName"
    },
    {
      align: "center",
      title: "所属岗位",
      dataIndex: "position"
    },
    {
      align: "center",
      title: "是否参与绩效考核",
      dataIndex: "participationEvalu",
      render: (_, record) => {
        return (
          <>
            {record.participationEvalu === "0" && <span>否</span>}
            {record.participationEvalu === "1" && <span>是</span>}
          </>
        )
      }
    },
    {
      align: "center",
      title: "操作",
      render: (_,record) => {
        return (
          <>
            <Button type={'link'} onClick={() => {
              setCurrentEdit(record)
              setId(record.id);
              record.positionId = Number(record.positionId)
              editForm.setFieldsValue(record)
              setSelectedValue(record.positionId);
              setSelectedLabel(record.position);
              setOpen(true);
            }}>编辑</Button>
          </>
        )
      }
    }
  ]

  const handleOk = async() => {
    try {
      const values = await editForm.validateFields();
      // 校验成功，执行保存操作并关闭Modal
      editSave(values);
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //编辑接口
  const editSave = async(data:object) =>{
    try {
      const res = await http.post({
        url:'/PmPositionPerson/update',
        data:{id:id,participationEvalu:data.participationEvalu,positionId:selectedValue,position:selectedLabel}
      })
      if(res.code==200){
        setOpen(false);
        message.success('岗位修改成功!');
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  const handleCancel = () => {
    setOpen(false);
  }

  //修改页码或分页大小
  const changePagination = async (page: number, size: number)=>{
    setPageNum(page);
    if(size!==pageSize){
      setPageNum(1);
    }
    setPageSize(size);
  }
  //查询接口
  const getList = async() =>{
    try {
      const res = await http.get({
        url:'/PmPositionPerson/pmPositionPersonList',
        params:{
          baseUserName:form.getFieldValue().baseUserName,
          pageNum:pageNum,
          pageSize:pageSize,
        }
      })
      setList(res.rows);
      setTotal(res.total);
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  const getPosition = async() =>{
    try {
      const res = await http.get({url:'/PmPosition/qryDropDownOptions'})
      setPositionOption(res.data)
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  const changePosition = (value)=>{
    // 查找选中的option
    const selectedOption = positionOption.find(option => option.id === value);
    setSelectedValue(value);
    setSelectedLabel(selectedOption ? selectedOption.position : '');
  }
  useEffect(()=>{
    getList();
    getPosition();
  },[pageNum,pageSize])
  return (
    <PageContainer>
      <ProForm form={form} layout={'inline'} onSearch={() => getList()}>
        <Form.Item
          label={'员工姓名'}
          name="baseUserName"
        >
          <Input placeholder="请输入员工姓名" />
        </Form.Item>
      </ProForm>

      <Table
        dataSource={list}
        columns={columns}
        rowKey={"field1"}
      ></Table>

      <Modal
        open={open}
        title="员工信息编辑"
        afterClose={() => editForm.resetFields()}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={'提交'}
        cancelText={'取消'}
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <CancelBtn />
            <OkBtn />
          </>
        )}
      >
        <Form form={editForm} initialValues={currentEdit} labelCol={{span: 7}}>
          <Form.Item
            label={'是否参与绩效考核'}
            name={'participationEvalu'}
            rules={[{ required: true, message: '请选择是否参与绩效考核!' }]}
          >
            <Radio.Group>
              <Radio value={'1'}>是</Radio>
              <Radio value={'0'}>否</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label={'所属岗位'}
            name={'positionId'}
            rules={[{ required: true, message: '请选择所属岗位!' }]}
          >
            <Select
              fieldNames={{ label: 'position', value: 'id' }}
              options={positionOption}
              onChange={changePosition}
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  )
}

export default PostMaintenance;
